/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:46:26
 * @LastEditTime: 2021-08-21 17:35:06
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \lua\luamap\map.go
 * hnxr
 */
package luamap

import (
	"encoding/json"

	"gitee.com/haodreams/golib/safe"
	lua "github.com/yuin/gopher-lua"
)

var smap = new(safe.StringMap)
var imap = new(safe.Int64Map)

func init() {
	smap.Init()
	imap.Init()
}

//Init 注册默认函数 函数接口
func Init(l *lua.LState) {
	l.SetGlobal("SetStringMap", l.NewFunction(SetStringMap))
	l.SetGlobal("GetStringMap", l.NewFunction(GetStringMap))
	l.SetGlobal("SetIntMap", l.NewFunction(SetIntMap))
	l.SetGlobal("GetIntMap", l.NewFunction(GetIntMap))
}

//SetStringMap .
func SetStringMap(l *lua.LState) int {
	key := l.CheckString(1)
	value := l.Get(2)
	smap.Set(key, value)
	return 0
}

//GetStringMap .
func GetStringMap(l *lua.LState) int {
	key := l.CheckString(1)
	val, ok := smap.Find(key)
	if ok {
		if value, ok := val.(lua.LValue); ok {
			l.Push(lua.LValue(value))
			return 1
		}
	}
	return 0
}

//SetIntMap .
func SetIntMap(l *lua.LState) int {
	key := l.CheckInt64(1)
	value := l.Get(2)
	imap.Set(key, value)

	return 0
}

//GetIntMap .
func GetIntMap(l *lua.LState) int {
	key := l.CheckInt64(1)
	val, ok := imap.Find(key)
	if ok {
		if value, ok := val.(lua.LValue); ok {
			l.Push(lua.LValue(value))
			return 1
		}
	}

	return 0
}

/**
 * @description: table 转 map
 * @param {*lua.LState} l
 * @return {*}
 */
func Table2Map(tab *lua.LTable) (m map[string]interface{}) {
	m = map[string]interface{}{}
	tab.ForEach(func(key lua.LValue, value lua.LValue) {
		if key.Type() == lua.LTString {
			m[key.String()] = value
		}
	})

	return
}

//table2JSON table 转为json
func Table2JSON(tab *lua.LTable) (string, error) {
	m := Table2Map(tab)
	return Map2JSON(m)
}

//Map2JSON 自动转换
func Map2JSON(m map[string]interface{}) (data string, err error) {
	b, err := json.MarshalIndent(m, "", "  ")
	data = string(b)
	return
}
